import { getAppByName } from '@/api/app';
import { useGlobalStore } from '@/store/global';
import { useGuideStore } from '@/store/guide';
import { useUserStore } from '@/store/user';
import { AppEditSyncedFields } from '@/types/app';
import { useRouter } from 'next/router';
import { useEffect, useRef } from 'react';

const RedirectPage = () => {
  const router = useRouter();
  const { setLastRoute } = useGlobalStore();
  const { resetGuideState } = useGuideStore();
  const { session } = useUserStore();
  const hasHandledRef = useRef(false);

  useEffect(() => {
    const handleRedirect = (formData?: string) => {
      if (formData) {
        try {
          const parsedData: Partial<AppEditSyncedFields> = JSON.parse(decodeURIComponent(formData));
          const appName = parsedData?.appName;
          if (appName) {
            getAppByName(appName)
              .then((app) => {
                setLastRoute(`/app/detail?name=${appName}`);
                router.replace({
                  pathname: '/app/edit',
                  query: { name: appName, formData }
                });
              })
              .catch((err) => {
                setLastRoute('/');
                router.replace({
                  pathname: '/app/edit',
                  query: { formData }
                });
              });
          } else {
            router.replace('/apps');
          }
        } catch (error) {
          console.error('解析formData失败:', error);
        }
      } else {
        router.replace('/apps');
      }
    };

    const handleUrlParams = () => {
      const { formData, action } = router.query as { formData?: string; action?: string };
      if (action === 'guide') {
        console.log('launchpad redirect', action);
        resetGuideState(false);
        router.replace('/apps?action=guide');
        return;
      }
      handleRedirect(formData);
    };

    // wait session
    if (router.isReady && session && !hasHandledRef.current) {
      hasHandledRef.current = true;
      handleUrlParams();
    }
  }, [resetGuideState, router, router.isReady, router.query, setLastRoute, session]);

  return null;
};

export default RedirectPage;
